package com.softstao.guoyu.ui.activity.me;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ericliu.asyncexpandablelist.CollectionView;
import com.ericliu.asyncexpandablelist.async.AsyncExpandableListView;
import com.ericliu.asyncexpandablelist.async.AsyncExpandableListViewCallbacks;
import com.ericliu.asyncexpandablelist.async.AsyncHeaderViewHolder;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.agent.Agent;
import com.softstao.guoyu.model.agent.AgentLevel;
import com.softstao.guoyu.model.agent.AgentList;
import com.softstao.guoyu.mvp.interactor.agent.AgentInteractor;
import com.softstao.guoyu.mvp.presenter.agent.AgentPresenter;
import com.softstao.guoyu.mvp.viewer.agent.AgentListViewer;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * Created by vaikus on 2017/7/3.
 */

public class ChooseAgentActivity extends BaseActivity implements AsyncExpandableListViewCallbacks<AgentLevel,Agent>,AgentListViewer {

    @AIPresenter(presenter = AgentPresenter.class, interactor = AgentInteractor.class)
    AgentPresenter presenter;

    @BindView(R.id.total_num)
    TextView totalNum;
    @BindView(R.id.expand_list)
    AsyncExpandableListView expandList;
    private CollectionView.Inventory<AgentLevel, Agent> inventory = new CollectionView.Inventory<>();
    private AgentList agentList;
    private List<AgentLevel> list = new ArrayList<>();

    @Override
    public int _ContentView() {
        return R.layout.activity_agent_list;
    }

    @Override
    public void initView() {
        initTitle("选择要充值的成员");
        expandList.setCallbacks(this);
    }

    private void initData(){
        totalNum.setText("下级代理人数：" + agentList.getTeamCount() + "人");

        list.clear();
        for (int i=0;i<4;i++){
            if (i==0) {
                AgentLevel level = new AgentLevel();
                level.setLevel(1);
                level.setAgentList(agentList.getAngelLevelList());
                level.setCount(agentList.getAngelLevelCount());
                list.add(level);
            }else if (i==1){
                AgentLevel level = new AgentLevel();
                level.setLevel(2);
                level.setAgentList(agentList.getCrownLevelList());
                level.setCount(agentList.getCrownLevelCount());
                list.add(level);
            }else if (i==2){
                AgentLevel level = new AgentLevel();
                level.setLevel(3);
                level.setAgentList(agentList.getOneLevelList());
                level.setCount(agentList.getOneLevelCount());
                list.add(level);
            }else if (i==3){
                AgentLevel level = new AgentLevel();
                level.setLevel(4);
                level.setAgentList(agentList.getCityLevelList());
                level.setCount(agentList.getCityLevelCount());
                list.add(level);
            }
        }
        Collections.reverse(list);

        CollectionView.InventoryGroup<AgentLevel,Agent> group1 = inventory.newGroup(0);
        group1.setHeaderItem(list.get(0));

        CollectionView.InventoryGroup<AgentLevel,Agent> group2 = inventory.newGroup(1);
        group2.setHeaderItem(list.get(1));

        CollectionView.InventoryGroup<AgentLevel,Agent> group3 = inventory.newGroup(2);
        group3.setHeaderItem(list.get(2));

        CollectionView.InventoryGroup<AgentLevel,Agent> group4 = inventory.newGroup(3);
        group4.setHeaderItem(list.get(3));

        expandList.updateInventory(inventory);
    }

    @Override
    protected void onResume() {
        super.onResume();
        findAgentList();
    }

    @Override
    public void onStartLoadingGroup(int groupOrdinal) {
        new LoadDataTask(groupOrdinal, expandList).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private class LoadDataTask extends AsyncTask<Void, Void, Void> {

        private int mGroupOrdinal;
        private WeakReference<AsyncExpandableListView<AgentLevel, Agent>> listviewRef = null;

        public LoadDataTask(int groupOrdinal, AsyncExpandableListView<AgentLevel, Agent> listview) {
            mGroupOrdinal = groupOrdinal;
            listviewRef = new WeakReference<>(listview);
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (listviewRef.get() != null) {
                listviewRef.get().onFinishLoadingGroup(mGroupOrdinal,list.get(mGroupOrdinal).getAgentList());
            }
        }
    }

    @Override
    public AsyncHeaderViewHolder newCollectionHeaderView(Context context, int groupOrdinal, ViewGroup parent) {
        View v = LayoutInflater.from(context)
                .inflate(R.layout.header_row_item_async, parent, false);

        return new MyHeaderViewHolder(v, groupOrdinal, expandList);
    }

    @Override
    public RecyclerView.ViewHolder newCollectionItemView(Context context, int groupOrdinal, ViewGroup parent) {
        View v = LayoutInflater.from(context)
                .inflate(R.layout.text_row_item_async, parent, false);

        return new NewsItemHolder(v);
    }

    @Override
    public void bindCollectionHeaderView(Context context, AsyncHeaderViewHolder holder, int groupOrdinal, AgentLevel headerItem) {
        MyHeaderViewHolder myHeaderViewHolder = (MyHeaderViewHolder) holder;
        String level_name = null;
        switch (headerItem.getLevel()){
            case 1:
                level_name = "天使";
                break;
            case 2:
                level_name = "皇冠";
                break;
            case 3:
                level_name = "一级";
                break;
            case 4:
                level_name = "市代";
                break;
        }
        myHeaderViewHolder.getTextView().setText(level_name);
        myHeaderViewHolder.getNumView().setText(String.valueOf(headerItem.getCount())+"人");
    }

    @Override
    public void bindCollectionItemView(Context context, RecyclerView.ViewHolder holder, int groupOrdinal, Agent item) {
        NewsItemHolder newsItemHolder = (NewsItemHolder) holder;
        String level_name = null;
        switch (item.getLevel()) {
            case 1:
                level_name = "天使";
                break;
            case 2:
                level_name = "皇冠";
                break;
            case 3:
                level_name = "一级";
                break;
            case 4:
                level_name = "市代";
                break;
        }
        newsItemHolder.getTextViewTitle().setText(item.getName());
        newsItemHolder.getTextViewDescrption().setText(level_name);
        newsItemHolder.setListener(() -> {
            Intent intent = new Intent(context,RechargeActivity.class);
            intent.putExtra("id",item.getId());
            startActivity(intent);
            finish();
        });
    }

    public static class MyHeaderViewHolder extends AsyncHeaderViewHolder implements AsyncExpandableListView.OnGroupStateChangeListener {

        private TextView textView;
        private TextView numView;
        private ProgressBar mProgressBar;
        private ImageView ivExpansionIndicator;

        public MyHeaderViewHolder(View v, int groupOrdinal, AsyncExpandableListView asyncExpandableListView) {
            super(v, groupOrdinal, asyncExpandableListView);
            textView = (TextView) v.findViewById(R.id.level);
            numView = (TextView) v.findViewById(R.id.num);
            mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar);
            mProgressBar.getIndeterminateDrawable().setColorFilter(0xFFFFFFFF,
                    android.graphics.PorterDuff.Mode.MULTIPLY);
            ivExpansionIndicator = (ImageView) v.findViewById(R.id.ivExpansionIndicator);
        }

        public TextView getTextView() {
            return textView;
        }

        public TextView getNumView() {
            return numView;
        }

        @Override
        public void onGroupStartExpending() {
            mProgressBar.setVisibility(View.VISIBLE);
            ivExpansionIndicator.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onGroupExpanded() {
            mProgressBar.setVisibility(View.GONE);
            ivExpansionIndicator.setVisibility(View.VISIBLE);
            ivExpansionIndicator.setImageResource(R.mipmap.list_btn_pull_up);
        }

        @Override
        public void onGroupCollapsed() {
            mProgressBar.setVisibility(View.GONE);
            ivExpansionIndicator.setVisibility(View.VISIBLE);
            ivExpansionIndicator.setImageResource(R.mipmap.list_btn_pull_down);
        }
    }

    public static class NewsItemHolder extends RecyclerView.ViewHolder {


        private final TextView tvTitle;
        private final TextView tvDescription;
        private NewsListener listener;

        public NewsItemHolder(View v) {
            super(v);
            v.setOnClickListener(v1 -> listener.itemClick());
            tvTitle = (TextView) v.findViewById(R.id.name);
            tvDescription = (TextView) v.findViewById(R.id.level);
        }

        public TextView getTextViewTitle() {
            return tvTitle;
        }

        public TextView getTextViewDescrption() {
            return tvDescription;
        }

        public interface NewsListener{
            void itemClick();
        }

        public NewsListener getListener() {
            return listener;
        }

        public void setListener(NewsListener listener) {
            this.listener = listener;
        }
    }

    @Override
    public void findAgentList() {
        presenter.getAllSub(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void getList(AgentList agentList) {
        if (agentList!=null){
            this.agentList = agentList;
            initData();
        }
    }
}
